﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OrderDesk.Areas.OrdersManagment.Models;
using BL;
using DA;
using OrderDesk.Controllers;
using BL.Membership;

namespace OrderDesk.Areas.OrdersManagment.Controllers
{
    [AuthorizePage(UserPermission.OrdersStation)]
    public class OrdersController : BaseController
    {
        public ActionResult Index()
        {
            var rep = new EmployeesRepository();

            OrdersModel model = new OrdersModel();
            model.EmpList = rep.GetEntitySet().ToList();

            return View(model);
        }

        [HttpPost]
        public JsonResult GetOrders()
        {
            OpenedOrdersModel model = new OpenedOrdersModel();

            var orders = 
                new OrdersRepository()
                .GetEntitySet()
                .Where(x =>
                    x.ClientId == CurrentUser.ClientId &&
                    x.OrderStatusNum != (int)OrderStatusEnum.Ordering &&
                    x.OrderStatusNum != (int)OrderStatusEnum.Taken)
                .ToList()
                .Select(x =>
                        new
                        {
                            orderStatus = x.OrderStatusNum,
                            orderId = x.OrderId,
                            count = x.ItemsInOrders.Count(),
                            date = x.CreationDate.ToString("hh:mm")
                        });

            model.FinishedOrders = orders.Where(x => x.orderStatus == (int)OrderStatusEnum.Finished);
            model.OnPrepOrders = orders.Where(x => x.orderStatus == (int)OrderStatusEnum.OnPreperation);
            model.PendingOrders = orders.Where(x => x.orderStatus == (int)OrderStatusEnum.Pending);

            return Json(model);
        }

        [HttpPost]
        public ActionResult PrepareOrder(int orderId, int preparingEmp)
        {
            var rep = new OrdersRepository();

            Order  order = rep.GetEntity(orderId);

            order.OrderStatusNum = (int)OrderStatusEnum.OnPreperation;

            //order.employeeId = preparingEmp;

            rep.Save(order);

            return Content("true");
        }

        [HttpPost]
        public ActionResult FinishOrder(int orderId)
        {
            var rep = new OrdersRepository();

            Order order = rep.GetEntity(orderId);

            order.OrderStatusNum = (int)OrderStatusEnum.Finished;

            rep.Save(order);

            return Content("true");
        }

        [HttpPost]
        public ActionResult OrderTaken(int orderId)
        {
            var rep = new OrdersRepository();

            Order order = rep.GetEntity(orderId);

            order.OrderStatusNum = (int)OrderStatusEnum.Taken;

            rep.Save(order);

            return Content("true");
        }
    }
}
